package com.xd.springaiagent.tools;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xd.springaiagent.tools.tavily.TavilySearchApi;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class WebSearchTool {

    @Autowired
    private TavilySearchApi  tavilySearchApi;

    /**
     * 使用Tavily进行AI搜索
     * @param query 搜索关键词
     * @param maxResults 最大返回结果数
     * @return JSON格式的搜索结果（失败时返回错误信息）
     */
    @Tool(name = "tavilySearch", description = "Search the web for information")
    public String tavilySearch(
            @ToolParam(description = "query keyword", required = true) String query,
            @ToolParam(description = "max results", required = true) int maxResults
    ) {
        try {
            List<Map<String, String>> results = tavilySearchApi.tavilySearch(query, maxResults);
            return new ObjectMapper().writeValueAsString(results);
        } catch (Exception e) {
            return "{\"error\":\"Search failed: " + e.getMessage() + "\"}";
        }
    }
}
